<template>
  <div class="container">
    <div class="header">
      <h1>轮播图管理</h1>
      <div class="actions">
        <el-button type="primary" @click="openBannerDialog()">添加轮播图</el-button>
        <el-button @click="refreshBannerList">刷新列表</el-button>
      </div>
    </div>
    
    <el-card class="banner-card">
      <el-table :data="bannerList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="轮播图" width="200">
          <template #default="scope">
            <div class="banner-preview" style="display: flex; flex-direction: column; align-items: center;">
              <el-image 
                :src="scope.row.bannerUrl" 
                style="width: 180px; height: 100px; object-fit: cover; border-radius: 4px;"
                :preview-src-list="[]"
              />
              <el-button type="primary" size="small" style="margin-top: 8px;" @click="handleTableImagePreview(scope.row.bannerUrl)">
                <el-icon><Picture /></el-icon> 预览
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="bannerTitle" label="标题" />
        <el-table-column prop="bannerDescription" label="描述" show-overflow-tooltip />
        <el-table-column prop="jumpUrl" label="跳转链接" width="200" show-overflow-tooltip />
        <el-table-column label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openBannerDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDeleteBanner(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 轮播图编辑对话框 -->
    <el-dialog
      :title="currentBanner.id ? '编辑轮播图' : '添加轮播图'"
      v-model="bannerDialogVisible"
      width="600px"
    >
      <el-form :model="currentBanner" label-width="100px" :rules="bannerRules" ref="bannerFormRef">
        <el-form-item label="轮播图标题" prop="bannerTitle">
          <el-input v-model="currentBanner.bannerTitle" placeholder="请输入轮播图标题" />
        </el-form-item>

        <el-form-item label="轮播图描述" prop="bannerDescription">
          <el-input v-model="currentBanner.bannerDescription" type="textarea" rows="3" placeholder="请输入轮播图描述" />
        </el-form-item>

        <el-form-item label="跳转链接" prop="jumpUrl">
          <el-input v-model="currentBanner.jumpUrl" placeholder="请输入跳转链接" />
        </el-form-item>

        <el-form-item label="轮播图片" prop="bannerUrl">
          <el-upload
            action="#"
            list-type="picture-card"
            :limit="1"
            :auto-upload="false"
            :on-change="handleBannerImageChange"
            accept="image/jpeg,image/png,image/gif"
            :file-list="bannerFileList"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div v-if="bannerImagePreview" class="image-preview-container">
            <el-image
              :src="bannerImagePreview"
              class="image-preview"
              style="width: 200px; height: 120px; object-fit: cover; cursor: pointer;"
              @click="handlePreviewBannerImage"
            />
            <el-button type="primary" size="small" style="margin-top: 8px;" @click="handlePreviewBannerImage">
              <el-icon><Picture /></el-icon> 预览大图
            </el-button>
          </div>
          <el-dialog v-model="previewVisible" title="图片预览" width="800px" append-to-body center>
            <div class="image-preview-dialog">
              <el-image
                style="width: 100%;"
                :src="bannerImagePreview"
                fit="contain"
              />
            </div>
          </el-dialog>
          <div class="upload-tip">
            <p>请上传轮播图片，建议尺寸 750x375 像素（宽高比2:1）</p>
            <p v-if="bannerImageFile || currentBanner.bannerUrl" style="color: #67C23A;">
              <el-icon><Check /></el-icon> 图片已选择，保存时将上传
            </p>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bannerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBanner" :loading="submitting">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, Check } from '@element-plus/icons-vue'
import { getAllBanners, getBannerById, addBanner, updateBanner, deleteBanner, uploadBannerImage } from '@/api/banner'

// 轮播图列表
const bannerList = ref([])
const loading = ref(false)
const bannerDialogVisible = ref(false)
const submitting = ref(false)
const bannerFormRef = ref(null)
const bannerFileList = ref([])
const bannerImagePreview = ref('')
const bannerImageFile = ref(null)
const previewVisible = ref(false)

// 当前正在编辑的轮播图
const currentBanner = reactive({
  id: null,
  bannerUrl: '',
  bannerTitle: '',
  bannerDescription: '',
  jumpUrl: '',
  deleteFlag: 0
})

// 轮播图表单校验规则
const bannerRules = {
  bannerTitle: [{ required: true, message: '请输入轮播图标题', trigger: 'blur' }],
  bannerDescription: [{ required: true, message: '请输入轮播图描述', trigger: 'blur' }],
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取轮播图列表
const fetchBannerList = async () => {
  loading.value = true
  try {
    const res = await getAllBanners()
    if (res && res.code === 200) {
      bannerList.value = res.data || []
    } else {
      ElMessage.error(res?.message || '获取轮播图列表失败')
    }
  } catch (error) {
    console.error('获取轮播图列表出错:', error)
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新轮播图列表
const refreshBannerList = () => {
  fetchBannerList()
}

// 打开轮播图对话框
const openBannerDialog = (banner) => {
  resetBannerForm()
  
  // 如果传入了banner，表示编辑
  if (banner) {
    Object.assign(currentBanner, banner)
    
    // 设置图片预览
    if (banner.bannerUrl) {
      bannerImagePreview.value = banner.bannerUrl
      bannerFileList.value = [
        {
          name: 'banner.jpg',
          url: banner.bannerUrl
        }
      ]
    }
  }
  
  bannerDialogVisible.value = true
}

// 重置轮播图表单
const resetBannerForm = () => {
  Object.assign(currentBanner, {
    id: null,
    bannerUrl: '',
    bannerTitle: '',
    bannerDescription: '',
    jumpUrl: '',
    deleteFlag: 0
  })
  bannerImageFile.value = null
  bannerImagePreview.value = ''
  bannerFileList.value = []
}

// 处理轮播图图片变化
const handleBannerImageChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('上传的文件必须是图片!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('上传的图片大小不能超过 2MB!')
    return false
  }
  
  bannerImageFile.value = file.raw
  bannerImagePreview.value = URL.createObjectURL(file.raw)
  return false
}

// 保存轮播图
const saveBanner = async () => {
  // 先校验表单
  if (!bannerFormRef.value) return
  
  try {
    await bannerFormRef.value.validate()
  } catch (error) {
    return
  }
  
  // 检查是否有图片
  if (!bannerImageFile.value && !currentBanner.bannerUrl) {
    ElMessage.error('请上传轮播图图片')
    return
  }
  
  submitting.value = true
  
  try {
    // 如果有新图片，先上传图片
    if (bannerImageFile.value) {
      console.log('开始上传图片...')
      const formData = new FormData()
      formData.append('file', bannerImageFile.value)
      
      const uploadRes = await uploadBannerImage(bannerImageFile.value)
      console.log('图片上传响应:', uploadRes) // 调试输出
      
      if (uploadRes && uploadRes.code === 200) {
        // 处理返回的文件路径（从message中获取，并去除多余空格）
        const imgPath = uploadRes.message ? uploadRes.message.replace(/\s+/g, '') : ''
        // 构建完整URL，确保路径没有多余空格
        currentBanner.bannerUrl = `http://localhost:8080/api${imgPath}`
        console.log('设置图片URL:', currentBanner.bannerUrl) // 调试输出
      } else {
        ElMessage.error(uploadRes?.message || '图片上传失败')
        submitting.value = false
        return
      }
    }
    
    if (!currentBanner.bannerUrl) {
      ElMessage.error('保存失败：轮播图图片URL为空')
      submitting.value = false
      return
    }
    
    console.log('保存轮播图数据:', JSON.stringify(currentBanner))
    
    // 保存轮播图信息
    let res
    if (currentBanner.id) {
      // 编辑
      console.log('更新轮播图数据:', currentBanner) // 调试输出
      res = await updateBanner(currentBanner)
    } else {
      // 新增
      console.log('新增轮播图数据:', currentBanner) // 调试输出
      res = await addBanner(currentBanner)
    }
    
    console.log('保存轮播图响应:', res) // 调试输出
    
    if (res && res.code === 200) {
      ElMessage.success('保存成功')
      bannerDialogVisible.value = false
      fetchBannerList() // 刷新列表
    } else {
      ElMessage.error(res?.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存轮播图出错:', error)
    ElMessage.error('保存失败: ' + (error.message || error))
  } finally {
    submitting.value = false
  }
}

// 确认删除轮播图
const confirmDeleteBanner = (banner) => {
  ElMessageBox.confirm(`确定要删除轮播图"${banner.bannerTitle}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDeleteBanner(banner.id)
  }).catch(() => {})
}

// 删除轮播图
const handleDeleteBanner = async (id) => {
  loading.value = true
  
  try {
    const res = await deleteBanner(id)
    if (res && res.code === 200) {
      ElMessage.success(res.message || '删除成功')
      fetchBannerList() // 刷新列表
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (error) {
    console.error('删除轮播图出错:', error)
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
  }
}

// 预览大图弹窗
const handlePreviewBannerImage = () => {
  previewVisible.value = true
}

// 预览大图弹窗
const handleTableImagePreview = (url) => {
  // 先关闭弹窗，确保每次都能刷新内容
  previewVisible.value = false
  // 立即赋值图片
  bannerImagePreview.value = url
  // 下一个tick再打开弹窗，确保图片已渲染
  setTimeout(() => {
    previewVisible.value = true
  }, 0)
}

onMounted(() => {
  fetchBannerList()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
    
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .banner-card {
    margin-bottom: 20px;
  }
  
  .banner-preview {
    display: flex;
    justify-content: center;
    padding: 5px;
  }
  
  .image-preview-container {
    margin-top: 10px;
  }
  
  .upload-tip {
    margin-top: 10px;
    color: #909399;
    font-size: 12px;
  }
}
</style> 